﻿using System.Data;
using System.Linq;

namespace CommonUtils
{
    public static class DataTableUtil
    {
        public static TableSchema GetSchema(this DataTable table)
        {
            var schema = new TableSchema();
            schema.Namespace = table.Namespace;
            schema.Comment = table.Prefix;
            schema.Name = table.TableName;
            foreach (DataColumn column in table.Columns)
            {
                var columnSchema = new ColumnSchema();
                columnSchema.Comment = column.Prefix;
                columnSchema.DataType = column.DataType;
                columnSchema.Nullable = column.AllowDBNull;
                columnSchema.Name = column.ColumnName;
                schema.Columns.Add(columnSchema);
            }
            return schema;
        }

        /// <summary>
        /// 非引用
        /// </summary>
        public static DataTable GetSelectedTable(this DataTable table, string columnName, string value)
        {
            var newTable = new DataTable();
            newTable.AddColumns(table);
            foreach (DataRow row in table.Rows)
            {
                if (row[columnName].ToString() == value)//一定要用值类型来比较
                    newTable.Rows.Add(row.ItemArray);
            }
            return newTable;
        }

        /// <summary>
        /// 非引用
        /// </summary>
        public static DataTable GetSelectedTable(this DataTable table, int columnIndex, string value)
        => table.GetSelectedTable(table.Columns[columnIndex].ColumnName, value);

        public static void AddRange(this DataColumnCollection newCollection, DataColumnCollection oldCollection)
        {
            foreach (DataColumn column in oldCollection)
                newCollection.Add(column.ColumnName, column.DataType);
        }

        public static void AddColumns(this DataTable newTable, DataTable table)
        => newTable.Columns.AddRange(table.Columns);

        public static void AddColumns(this DataTable table, params string[] columns)
        => table.Columns.AddRange(columns.Select(m => new DataColumn(m, typeof(string))).ToArray());

        public static void AddColumn(this DataTable table, string column)
        => table.Columns.Add(column);

        public static void AddRow(this DataTable table, params object[] cells)
        //=> newTable.ImportRow(newTable.LoadDataRow(cells, true));//两次
        => table.LoadDataRow(cells, true);
    }
}
